package com.example.viewmodel;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.ScrollView;

import androidx.annotation.Nullable;
import androidx.databinding.BaseObservable;
import androidx.databinding.ObservableField;

import com.example.websocket.HeartBeatGenerateCallback;
import com.example.websocket.ImproperCloseException;

import com.example.websocket.NetworkUtil;
import com.example.websocket.RxWebSocket;
import com.example.websocket.RxWebSocketBuilder;
import com.example.websocket.WebSocketInfo;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import io.reactivex.ObservableEmitter;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;


public class WSSocketViewModel extends BaseObservable {
    private final OkHttpClient okHttpClient;
    private boolean isConnect = false;

    private  Context context;
    private final String TAG="WSSocketViewModel";
    private final String mWebSocketUrl;
    public ObservableField<String> info = new ObservableField<>();
    public ObservableField<String> sendMsg=new ObservableField<>();
    private final ScrollView scrollView;
    RxWebSocket rxWebSocket;

    public WSSocketViewModel(String wssUrl, Context context, ScrollView scrollView){
        this.context=context;
        this.mWebSocketUrl =wssUrl;
        this.scrollView=scrollView;
        okHttpClient = new OkHttpClient.Builder()
                .readTimeout(3, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(3, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(3, TimeUnit.SECONDS)//设置连接超时时间
                .build();

        rxWebSocket = new RxWebSocketBuilder(context)
                //5秒无响应则重连
                .reconnectInterval(5, TimeUnit.SECONDS)
                .client(okHttpClient)
                .build();
//        info.set("正在连接");
//        mWebSocket = okHttpClient.newWebSocket(request, new WsListener());
        createConnect();
    }
    private void createConnect(){
        info.set("正在连接");

        rxWebSocket.get(mWebSocketUrl)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<WebSocketInfo>() {
                    @Override
                    public void accept(WebSocketInfo webSocketInfo) throws Exception {
                        if(!isConnect) {
                            isConnect = webSocketInfo.isConnect();
                            if(isConnect){
                                appendInfo("\n连接成功\n");
                            }
                        }
                        String msg = webSocketInfo.getStringMsg();
                        if(msg!=null) {
                            appendInfo("\n收到：\n    " + msg + "\n");
                            Log.d(TAG,"\n收到：\n    " + msg + "\n");
                        }
                    }
                });

        rxWebSocket.heartBeat(mWebSocketUrl, 6 ,TimeUnit.SECONDS, timestamp -> {
            String jsonStr=new Gson().toJson(new HeartBeatMsgRequestModel(String.valueOf(timestamp / 1000)));
            Log.d(TAG, "心跳："+jsonStr);
            return jsonStr;
        }).subscribe();

    }
    public void appendInfo(String info){
        this.info.set(this.info.get()+info);
        scrollView.fullScroll(View.FOCUS_DOWN);
    }
    public void onSendClick(View v){
        String msg=sendMsg.get();
        if(msg==null || msg.length()==0 || !rxWebSocket.isConnect(mWebSocketUrl)){
            return;
        }
        appendInfo("\n发送：\n    "+sendMsg.get()+"\n");
        Log.d(TAG, "发送: "+sendMsg.get());
        send(sendMsg.get());


    }


    //发送String消息
    public void send(final String message) {
        rxWebSocket.asyncSend(mWebSocketUrl, message)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean isSuccess) throws Exception {
                        if(isSuccess) {
                            sendMsg.set("");
                        } else {
                            appendInfo("发送失败!\n");
                        }
                    }
                });
    }


    //主动断开连接
    public void disconnect(int code, String reason) {
        if (rxWebSocket != null)
            rxWebSocket.closeAllNow();
    }


}
